package top.infopub.mgr.fia.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.infopub.dto.fia.FundsAppnDto;
import top.infopub.enums.fia.FiaProcessDetailTypeEnum;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.enums.mkt.ProjectFileTypeEnum;
import top.infopub.generic.GenericDao;
import top.infopub.generic.GenericServiceImpl;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.fia.dao.CommonDao;
import top.infopub.mgr.fia.dao.FundsAppnDao;
import top.infopub.mgr.fia.domain.FundsAppnDomain;
import top.infopub.mgr.fia.jsonvo.FundsAppnJsonVo;
import top.infopub.mgr.fia.service.BankInfoService;
import top.infopub.mgr.fia.service.FiaProcessManageService;
import top.infopub.mgr.fia.service.FundsAppnService;
import top.infopub.mgr.fia.vo.FundsAppnVo;
import top.infopub.mgr.flow.service.OAFlowService;
import top.infopub.mgr.hr.dao.StaffInfoDao;
import top.infopub.mgr.mkt.dao.ProjectAttachmentDao;
import top.infopub.mgr.mkt.service.SetupProService;
import top.infopub.model.common.HrOrgInfo;
import top.infopub.model.common.ProInfo;
import top.infopub.model.fia.BankInfo;
import top.infopub.model.fia.FiaProcessDetail;
import top.infopub.model.fia.FundsAppn;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import java.util.Date;
import java.util.List;

@Service
public class FundsAppnServiceImpl extends GenericServiceImpl<FundsAppn, String> implements
		FundsAppnService {

	@Autowired
	private FundsAppnDao fundsAppnDao;

	@Autowired
	private CommonDao commonDao;

	@Autowired
	private StaffInfoDao staffInfoDao;

	@Autowired
	private ProjectAttachmentDao projectAttachmentDao;

	@Autowired
	private SetupProService setupProService;

	@Autowired
	private OAFlowService oaFlowService;

	@Autowired
	private FiaProcessManageService fiaProcessManageService;

	@Autowired
	private BankInfoService bankInfoService;
	
	@Override
	public GenericDao<FundsAppn, String> getDao() {
		return fundsAppnDao;
	}
	
	@Override
    public Page<FundsAppnDomain> selectPageByDomainWhere(Page<FundsAppnDomain> page,
                                                         FundsAppnVo fundsAppnVo) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        return (Page<FundsAppnDomain>)fundsAppnDao.selectByDomainWhere(fundsAppnVo);
    }

	@Override
	public FundsAppnJsonVo queryDetailById(String id) {
		FundsAppnJsonVo fundsAppnJson = new FundsAppnJsonVo();
		if (StringUtils.isNotBlank(id)) {
			//基础信息
			FundsAppnDto fundsAppnDto = fundsAppnDao.queryDetailById(id);
			fundsAppnJson.setInfo(fundsAppnDto);

			//附件信息表
			List<ProjectAttachment> projectAttaList = projectAttachmentDao.queryByWhere(fundsAppnDto.getId(), ProjectFileTypeEnum.FILE_TYPE61.getCode(), null);
			fundsAppnJson.setFileAtt(setupProService.fileAttaListToArray(projectAttaList));
		} else {
			//基础信息
			FundsAppnDto fundsAppnDto = new FundsAppnDto();
			AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
			StaffInfo staffInfo = staffInfoDao.selectByPrimaryKey(vo.getHrStaffId());
			if (staffInfo == null) {
				fundsAppnDto.setStaffName(vo.getRealName());
			} else {
				fundsAppnDto.setStaffName(staffInfo.getStaffName());
			}
			fundsAppnJson.setInfo(fundsAppnDto);

			//项目信息列表
			List<ProInfo> proInfoList = commonDao.queryCapSetupProList(ProProcesssStatusEnum.PRO_STATUS9.getCode());
			fundsAppnJson.setProInfoList(proInfoList);
		}
		//银行信息列表
		List<BankInfo> bankInfoList = bankInfoService.queryBankInfoList("1");
		fundsAppnJson.setBankInfoList(bankInfoList);
		//组织架构单位列表
		List<HrOrgInfo> orgInfoList = commonDao.queryHrOrgInfoList(null);
		fundsAppnJson.setOrgInfoList(orgInfoList);
		return fundsAppnJson;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public RspVo edit(FundsAppnDto fundsAppnDto, List<ProjectAttachment> attachmentList, Integer submitType, AuthorizationVO vo) {
		FundsAppn tmpFa = new FundsAppn();
		FundsAppn fundsAppn = new FundsAppn();
		BeanUtils.copyProperties(fundsAppnDto, fundsAppn);
		if (StringUtils.isNotBlank(fundsAppnDto.getId())) {
			//校验资金上交数据是否存在
			tmpFa = fundsAppnDao.selectByPrimaryKey(fundsAppnDto.getId());
			if (tmpFa == null) return RspVo.getFailureResponse(400, "资金上交数据不存在");
			//判断审批状态
			if (StringUtils.isNotBlank(tmpFa.getProcessStatus())
					&& (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpFa.getProcessStatus())
					|| StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), tmpFa.getProcessStatus()))) {
				return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
			}
			fundsAppn.setUptBy(vo.getId());
			fundsAppn.setUptTime(new Date());
			fundsAppnDao.updateByIdSelective(fundsAppn);
		} else {
			fundsAppn.setCodes(IdFactory.getUUIDUpper());
			fundsAppn.setAddBy(vo.getId());
			fundsAppn.setAddTime(new Date());
			fundsAppn.setUptBy(vo.getId());
			fundsAppn.setUptTime(new Date());
			fundsAppnDao.insertSelective(fundsAppn);
		}

		//更新附件信息
		projectAttachmentDao.deleteByWhere(fundsAppn.getId(), ProjectFileTypeEnum.FILE_TYPE60.getCode(), null);
		if (attachmentList != null && attachmentList.size() > 0) {
			projectAttachmentDao.insertBatch(attachmentList);
		}

		if (submitType == 1) {
			if (org.apache.commons.lang.StringUtils.isNotBlank(tmpFa.getOaId())) {
				oaFlowService.finishOA(tmpFa.getOaId());
			}
			FundsAppnJsonVo fundsAppnJson = queryDetailById(fundsAppn.getId());
			fundsAppnJson.setProInfoList(null);
			fundsAppnJson.setOrgInfoList(null);
			fundsAppnJson.setBankInfoList(null);
			String detailJson = JSON.toJSONString(fundsAppnJson);
			fiaProcessManageService.sendProcess(FiaProcessDetailTypeEnum.PRO_NODE_TYPE7, detailJson, fundsAppn.getId(), fundsAppn.getProCode(), vo);
		}
		return RspVo.getSuccessResponse();
	}

	@Override
	public RspVo modifyFinInfo(FundsAppn fundsAppn, AuthorizationVO vo, String processId) {
		//校验资金上交数据是否存在
		FundsAppn tmpFa = fundsAppnDao.selectByPrimaryKey(fundsAppn.getId());
		if (tmpFa == null) return RspVo.getFailureResponse(400, "融资付息数据不存在");
		//判断审批状态
		if (!(StringUtils.isNotBlank(tmpFa.getProcessStatus())
				&& StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), tmpFa.getProcessStatus()))) {
			return RspVo.getFailureResponse(400, "审批状态不正确，操作失败");
		}

		fundsAppn.setUptBy(vo.getId());
		fundsAppn.setUptTime(new Date());
		//更新信息
		fundsAppnDao.updateByIdSelective(fundsAppn);

		FiaProcessDetail fpd = fiaProcessManageService.queryByProcessId(processId);
		FundsAppnJsonVo fundsHandJson = JSON.parseObject(fpd.getDetailJson(), FundsAppnJsonVo.class);
		fundsHandJson.getInfo().setActualAmt(fundsAppn.getActualAmt());
		fundsHandJson.getInfo().setActualDate(fundsAppn.getActualDate());
		fundsHandJson.getInfo().setBankName(fundsAppn.getBankName());
		fundsHandJson.getInfo().setAccountNo(fundsAppn.getAccountNo());
		fundsHandJson.getInfo().setReceiverName(fundsAppn.getReceiverName());
		fundsHandJson.getInfo().setReceiverNo(fundsAppn.getReceiverNo());
		fundsHandJson.getInfo().setFinMemo(fundsAppn.getFinMemo());
		fiaProcessManageService.modifyDetailJsonById(fpd);

		return RspVo.getSuccessResponse();
	}
}